<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.searchKey"
        placeholder="标题"
        style="width: 200px"
        class="filter-item"
      />
      <el-select
        v-model="listQuery.sortKey"
        style="width: 140px"
        class="filter-item"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="searchAndSort"
      >
        查找
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="$router.push(`/projectdeclare/create`)"
      >
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        label="序列号"
        prop="id"
        sortable="custom"
        align="center"
        width="100"
        :class-name="getSortClass('idNumber')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.idNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="100px" align="center">
        <template slot-scope="{ row }">
          <span>{{
            row.projectDeclareName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名开始时间" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.projectDeclareStart | convertUTCToGMTString }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名结束时间" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.projectDeclareEnd | convertUTCToGMTString }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button
            v-if="checkPermission(['项目申报信息：浏览'])"
            size="mini"
            type="success"
            @click="$router.push(`/projectdeclare/view/${row.id}`)"
          >
            查看
          </el-button>
          <el-button
            v-if="checkPermission(['项目申报信息：更新'])"
            type="primary"
            size="mini"
            @click="$router.push(`/projectdeclare/edit/${row.id}`)"
          >
            编辑
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button
            v-if="checkPermission(['项目申报信息：删除'])"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
          <el-button
            v-if="checkPermission(['项目信息：创建']) && checkDate(row.projectDeclareEnd)"
            size="mini"
            type="warning"
            @click="$router.push(`/project/create/${row.id}/declare/${row.projectDeclareName}`)"
          >
            申请
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageIndex"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { parseTime, findAll } from "@/utils";
import Pagination from "@/components/Pagination";
import { fetchProjectDeclareList, deleteProjectDeclare } from "@/api/project-declare";
import { checkPermission, checkDate } from '@/utils/permission'
import { mapGetters } from "vuex";

export default {
  name: "projectDeclareList",
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      totalList: null,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageIndex: 1,
        limit: 10,
        searchField: 'projectDeclareName',
        searchKey: '',
        sortField: 'idNumber',
        sortKey: "asce",
      },
      sortOptions: [
        { label: "序列号 升序", key: "asce" },
        { label: "序列号 降序", key: "desc" },
      ]
    };
  },
  computed: {
    ...mapGetters(["id", "name", "roles"]),
  },
  created() {
    this.getList();
  },
  filters: {
    convertUTCToGMTString(val) {
      if (!val) return '';
      const currentDate = new Date(val);
      const month =
        currentDate.getMonth() < 9
          ? `0${currentDate.getMonth() + 1}`
          : (currentDate.getMonth()+1).toString();
      return `${currentDate.getFullYear()}-${month}-${currentDate.getDate()}`;
    },
  },
  methods: {
    checkPermission,
    checkDate,
    getList() {
      this.listLoading = true;
      fetchProjectDeclareList().then(res => {
        this.totalList = res.data.map((item, index) => {
          item.idNumber = index + 1;
          return item;
        });
        this.handleFilter();

        this.listLoading = false;
      })
    },
    handleFilter() {
      const result=findAll(this.totalList, this.listQuery);
      this.list = result.data;
      this.total=result.total;
    },
    searchAndSort() {
      this.listQuery.pageIndex = 1;
      this.handleFilter();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sortKey = "asce";
      } else {
        this.listQuery.sortKey = "desc";
      }
      this.listQuery.pageIndex = 1;
      this.handleFilter();
    },
    handleDelete(row, index) {
      this.$confirm(`是否确定删除 "${row.projectDeclareName}"`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
          deleteProjectDeclare(row.id).then((res) => {
            if (res.data) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //重新获取
              this.getList();
            } else {
              this.$message({
                message: "项目申报信息删除失败",
                type: "error",
              });
            }
          })
          .catch((err) => {
            this.$message({
              message: "项目申报信息删除失败",
              type: "error",
            });
          });
      });
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sortKey;
      return sort === `asce` ? "ascending" : "descending";
    },
  },
};
</script>
